package top.infopub.mgr.mkt.web;


import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.hr.service.StaffOfficeService;
import top.infopub.mgr.hr.vo.StaffOfficeVo;
import top.infopub.mgr.mkt.domain.PreProjectDomain;
import top.infopub.mgr.mkt.domain.ProjectDomain;
import top.infopub.mgr.mkt.jsonvo.CollectJsonVo;
import top.infopub.mgr.mkt.service.PreProjectService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.vo.CollectProjectVo;
import top.infopub.mgr.mkt.vo.PreProjectVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.FirstSpellUtil;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.PreProject;
import top.infopub.model.mkt.PreProjectAtt;
import top.infopub.model.mkt.PreProjectCoop;
import top.infopub.model.mkt.PreProjectSub;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 预立项管理
 * @author wangw
 * @version 2020年1月2日
 * @see PreProjectController
 * @since
 */
@Controller
@RequestMapping("/preProject")
public class PreProjectController extends GenericFlowController {

    @Autowired
    private PreProjectService preProjectService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private StaffOfficeService staffOfficeService;

    @Autowired
    private CoopInfoService coopInfoService;

   @Autowired
   private ProProcessManageService proProcessManageService;

    /**
     * 预立项列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "mkt/lay-preProject-list";
    }

    /**
     * 预立项列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ProjectDomain> queryDataByCondition(CollectProjectVo collectProjectVo,
                                                     ParamPage paramPage) {
        Page<ProjectDomain> page = new Page<ProjectDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = preProjectService.selectPageByDomainWhere(page, collectProjectVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }


    /**
     * 根据id查询预立项详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 预立项Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String queryByIdd(HttpServletRequest request, String id, String proCode) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id",id);
        PreProject preProject = preProjectService.selectByPrimaryKey(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        if (preProject != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), preProject.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), preProject.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(preProject.getProcessId()) && preProject.getProcessId().length() > 10) {
                request.setAttribute("processId", preProject.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(preProject.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), preProject.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("proCode",proCode);
        return "mkt/lay-preProject-detail";
    }

    /***
     *
     * 预立项详情
     * ***/
    @RequestMapping("/queryPreDetail")
    @ResponseBody
    public RspVo queryPreDetail(String id) {
        //项目详情信息
        CollectJsonVo collectJsonVo = preProjectService.queryDetailById(id);
        return RspVo.getSuccessResponse(collectJsonVo);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //预立项审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 预立项-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<PreProjectDomain> queryMyCheckDataByCondition(PreProjectVo preProjectVo,
                                                               ParamPage paramPage) {
        Page<PreProjectDomain> page = new Page<PreProjectDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (preProjectVo.getEndDate() != null) {
            preProjectVo.setEndDate(DateUtils.addDays(preProjectVo.getEndDate(), 1));
        }
        preProjectVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = preProjectService.selectMyCheckByDomainWhere(page, preProjectVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }


//    /***
//     * *审批页面**
//     *
//     * ***/
//    @RequestMapping("/toDealOrDetail")
//    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
//        request.setAttribute("id",id);
//        request.setAttribute("proCode",proCode);
//        return "mkt/lay-preProject-process";
//    }


    /**
     * 预立项-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        String bindOrgId = (String)SessionUserUtils.getSessionAttribute("bindOrgId");
        String bindOrgName = (String)SessionUserUtils.getSessionAttribute("bindOrgName");
        request.setAttribute("areaFirstSpell", FirstSpellUtil.two(bindOrgName));
        //查询有效的营销经理记录
        List<StaffOfficeVo> staffOfficeVos = staffOfficeService.selectActiveByOrgId(bindOrgId);
        request.setAttribute("staffOfficeVos", staffOfficeVos);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-preProject-add_temp";
    }

//    /**
//     * 根据id查询预立项详情  > 注意：方法命名必须为：toDealOrDetail
//     * @param id 预立项Id
//     * @return
//     * @see
//     */
//    @RequestMapping("/toDealOrDetail")
//    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
//        request.setAttribute("id",id);
//        return new ModelAndView("mkt/lay-preProject-add");
//    }

    @RequestMapping("/toDetail")
    public String queryDetailById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        PreProjectVo collectProject = preProjectService.selectById(id);
        request.setAttribute("pro", collectProject);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        request.setAttribute("edit", "edit");
        //查询底线标准
//        String sgCityId = collectProject.getSgCityId();
//        List<BaseLineVo> baseLines = baseLineService.selectBySgCityId(sgCityId,2,collectProject);
//        request.setAttribute("baseLines", baseLines);
        return "mkt/lay-preProject-add";
    }

    /**
     * 预立项-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request,String id) {
        PreProjectVo preProject = preProjectService.selectById(id);
        request.setAttribute("preProject", preProject);
        String bindOrgId = (String)SessionUserUtils.getSessionAttribute("bindOrgId");
//        String bindOrgName = preProject.getAreaName();
//        request.setAttribute("areaFirstSpell", FirstSpellUtil.two(bindOrgName));
        //查询有效的营销经理记录
        List<StaffOfficeVo> staffOfficeVos = staffOfficeService.selectActiveByOrgId(bindOrgId);
        request.setAttribute("staffOfficeVos", staffOfficeVos);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-preProject-copy";
    }


//    /**
//     * 新增预立项
//     * @return
//     */
//    @SuppressWarnings({"rawtypes"})
//    @RequestMapping("/save")
//    public @ResponseBody RspVo save(String bodyStr,Integer submitType){
//        AuthorizationVO userDtl = SessionUserUtils.getSessionAttributeForUserDtl();
//        String s = StringEscapeUtils.unescapeJava(bodyStr);
//        CollectionInfoVo vo = JSON.parseObject(s,CollectionInfoVo.class);
//
//        //处理项目基础信息
//        ProjectInfo projectInfo = new ProjectInfo();
//        BeanUtils.copyProperties(vo.getProjectInfo(),projectInfo);
//
//        PreProject preProject = preProjectService.selectByProCode1(projectInfo.getProCode());
//        //更新预立项信息
//        preProject.setUptBy(userDtl.getId());
//        preProject.setUptTime(new Date());
//
//        //处理合作单位信息
//        List<AfterSummaryCoop> summary = vo.getSummary();
//        for (AfterSummaryCoop summaryCoop : summary) {
//            summaryCoop.setId(IdFactory.getUUIDUpper());
//            summaryCoop.setProCode(vo.getProjectInfo().getProCode());
//            summaryCoop.setAddBy(userDtl.getId());
//            summaryCoop.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        }
//
//        //更新项目子项表格信息-MKT_PROJECT_SUB_INFO
//        ProjectSubInfo proSubInfo = new ProjectSubInfo();
//        proSubInfo.setProCode(projectInfo.getProCode());
//        proSubInfo.setTitleJson(JSON.toJSONString(vo.getItemName()));
//        proSubInfo.setContentJson(JSON.toJSONString(vo.getInvestmentInfoVos()));
//        StringBuffer rowTotal = new StringBuffer();
//        StringBuffer colTotal = new StringBuffer();
//        int itivIdx = 0;
//        int itivSize = vo.getInvestmentInfoVos().size();
//        for (InvestmentInfoVo itiv : vo.getInvestmentInfoVos()) {
//            if (itivIdx == (itivSize - 1)) {
//                for (Long tmpTotal : itiv.getList()) {
//                    rowTotal.append(tmpTotal);
//                    rowTotal.append(",");
//                }
//                rowTotal.append(itiv.getTotal());
//            }
//            if (itivIdx > 2) {
//                colTotal.append(itiv.getTotal());
//                colTotal.append(",");
//            }
//            itivIdx++;
//        }
//        if (colTotal.length() > 0) colTotal.deleteCharAt(colTotal.length() - 1);
//        proSubInfo.setRowTotal(rowTotal.toString());
//        proSubInfo.setColTotal(colTotal.toString());
//        proSubInfo.setUptBy(userDtl.getId());
//        proSubInfo.setUptTime(new Date());
//
//        //更新项目风险信息-MKT_PROJECT_RISK
//        List<ProjectRisk> riskList = vo.getProjectRisk();
//
//        //更新附件表-MKT_PROJECT_ATTACHMENT
//        List<ProjectAttachment> attachmentList = new ArrayList<>();
//        if(vo.getFileAtt()!=null){
//            String[] fileAtt = vo.getFileAtt();
//            for (String file : fileAtt) {
//                ProjectAttachment attachment = createProjectFileAtta(userDtl, vo.getProjectInfo().getProCode(), file);
//                attachmentList.add(attachment);
//            }
//        }
//        preProjectService.saveAll(projectInfo,preProject,summary,proSubInfo,riskList,attachmentList,userDtl);
//        return RspVo.getSuccessResponse();
//    }
//    public @ResponseBody RspVo save(HttpServletRequest request, PreProject preProject) {
//        //判断项目名称是否存在
//        List<PreProject> preProjects = preProjectService.selectByProName(preProject.getProName());
//        if(CollectionUtils.isNotEmpty(preProjects)){
//            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("项目名称【" + preProject.getProName()
//                + "】已经存在~");
//        }
//        String fromChannel = request.getParameter("fromChannel");//项目渠道
//        String linkPower = request.getParameter("linkPower");//居住地址
//        if (fromChannel.equals("2")) {//居间合作
//            if (StringUtils.isEmpty(linkPower)) {
//                return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("居间方不能为空");
//            }
//        }
//        String[] sgCoopId = request.getParameterValues("sgCoopId");//单位名称
//        String[] coopEffect = request.getParameterValues("coopEffect");//单位作用
//
//        String[] orderIdx = request.getParameterValues("orderIdx");//子项序号
//        String[] subName = request.getParameterValues("subName");//子项名称
//        String[] subWorkYears = request.getParameterValues("subWorkYears");//子项-合作周期（年）
//        String[] subBuildYears = request.getParameterValues("subBuildYears");//子项-建设周期（年）
//        String[] subOmYears = request.getParameterValues("subOmYears");//子项-运营周期（年）
//
//        String[] fileAtt1 = request.getParameterValues("fileAtt1");
//        String[] fileAtt2 = request.getParameterValues("fileAtt2");
//        String[] fileAtt9 = request.getParameterValues("fileAtt9");
//
//        if (sgCoopId != null && sgCoopId.length > 0) {
//            for (int i = 0; i < sgCoopId.length; i++ ) {
//                String coopId = sgCoopId[i];
//                String coopeffect = coopEffect[i];
//                if (StringUtils.isNotEmpty(coopId)) {
//                    if (StringUtils.isEmpty(coopeffect)) {
//                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位作用未选择");
//                    }
//                }
//                else {
//                    if (StringUtils.isNotEmpty(coopeffect)) {
//                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位名称未选择");
//                    }
//                }
//            }
//        }
//
//        if (fileAtt1 == null || fileAtt1.length < 1) {
//            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("项目可研报告未上传");
//        }
//        if (fileAtt2 == null || fileAtt2.length < 1) {
//            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("两评一案未上传");
//        }
//
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//
//        /**
//         * 预立项主表处理
//         */
//        String id = IdFactory.getUUIDUpper();
//        preProject.setId(id);
//        preProject.setAddBy(vo.getId());
//        preProject.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String codes = codeGeneratorConfigService.generatorCode("mkt_pre_project_codes");
//        preProject.setCodes(codes);
//        // 处理processId
//        preProject.setProcessId(IdFactory.getUUIDUpper());
//        preProject.setProcessStatus("1");//审批中
//        String proCode = codeGeneratorConfigService.generatorCode("mkt_pre_project_procode");
//        preProject.setProCode("JT-" + preProject.getAreaFirstSpell() + "-" + proCode);
//        preProject.setUptBy(vo.getId());
//        preProject.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //合作单位处理
//        List<PreProjectCoop> preProjectCoops = new ArrayList<PreProjectCoop>();
//        if (sgCoopId != null && sgCoopId.length > 0) {
//            for (int i = 0; i < sgCoopId.length; i++ ) {
//                String coopId = sgCoopId[i];
//                String coopeffect = coopEffect[i];
//                if (StringUtils.isEmpty(coopId) && StringUtils.isEmpty(coopeffect)) {
//                    continue;
//                }
//                String coopid = IdFactory.getUUIDUpper();//自动生成主键
//                PreProjectCoop preProjectCoop = new PreProjectCoop();
//                preProjectCoop.setId(coopid);
//                preProjectCoop.setPreProjectId(id);
//                preProjectCoop.setSgCoopId(coopId);
//                preProjectCoop.setCoopEffect(coopeffect);
//                preProjectCoop.setAddBy(vo.getId());
//                preProjectCoop.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                preProjectCoops.add(preProjectCoop);
//            }
//
//        }
//
//        //子项处理
//        List<PreProjectSub> preProjectSubs = new ArrayList<PreProjectSub>();
//        for (int i = 0; i < orderIdx.length; i++ ) {
//            String orderId = orderIdx[i];
//            PreProjectSub preProjectSub = new PreProjectSub();
//            String subId = IdFactory.getUUIDUpper();//自动生成主键
//            preProjectSub.setId(subId);
//            preProjectSub.setPreProjectId(id);
//            preProjectSub.setOrderIdx(Integer.parseInt(orderId));
//            preProjectSub.setSubName(subName[i]);
//            preProjectSub.setWorkYears(new BigDecimal(subWorkYears[i]));
//            preProjectSub.setBuildYears(new BigDecimal(subBuildYears[i]));
//            preProjectSub.setOmYears(new BigDecimal(subOmYears[i]));
//            preProjectSub.setAddBy(vo.getId());
//            preProjectSub.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//            preProjectSubs.add(preProjectSub);
//        }
//        /**
//         * 上传的文件记录加入集合
//         */
//        List<PreProjectAtt> fileAtts = new ArrayList<PreProjectAtt>();
//        //项目可研报告
//        if (fileAtt1 != null) {
//            for (String file : fileAtt1) {
//                PreProjectAtt preProjectAtt = createFileAtt(vo, id, file);
//                fileAtts.add(preProjectAtt);
//            }
//        }
//        //两评一案
//        if (fileAtt2 != null) {
//            for (String file : fileAtt2) {
//                PreProjectAtt preProjectAtt = createFileAtt(vo, id, file);
//                fileAtts.add(preProjectAtt);
//            }
//        }
//        //其他资料（选填）
//        if (fileAtt9 != null) {
//            for (String file : fileAtt9) {
//                PreProjectAtt preProjectAtt = createFileAtt(vo, id, file);
//                fileAtts.add(preProjectAtt);
//            }
//        }
//        preProjectService.addPreProject(preProject, preProjectCoops, preProjectSubs, fileAtts);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
//            "预立项 -新增预立项：项目名=" + preProject.getProName(), null);
//        return RspVo.getSuccessResponse();
//    }

    /**
     * 编辑预立项
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(HttpServletRequest request, PreProject preProject) {

        String submitType = request.getParameter("submitType");//2=提交  1保存

        String fromChannel = request.getParameter("fromChannel");//项目渠道
        String linkPower = request.getParameter("linkPower");//居住地址
        if (fromChannel.equals("2")) {//居间合作
            if (StringUtils.isEmpty(linkPower)) {
                return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("居间方不能为空");
            }
        }
        String[] sgCoopId = request.getParameterValues("sgCoopId");//单位名称
        String[] coopEffect = request.getParameterValues("coopEffect");//单位作用

        String[] orderIdx = request.getParameterValues("orderIdx");//子项序号
        String[] subName = request.getParameterValues("subName");//子项名称
        String[] subWorkYears = request.getParameterValues("subWorkYears");//子项-合作周期（年）
        String[] subBuildYears = request.getParameterValues("subBuildYears");//子项-建设周期（年）
        String[] subOmYears = request.getParameterValues("subOmYears");//子项-运营周期（年）

        String[] fileAtt1 = request.getParameterValues("fileAtt1");
        String[] fileAtt2 = request.getParameterValues("fileAtt2");
        String[] fileAtt9 = request.getParameterValues("fileAtt9");

        if (sgCoopId != null && sgCoopId.length > 0) {
            for (int i = 0; i < sgCoopId.length; i++ ) {
                String coopId = sgCoopId[i];
                String coopeffect = coopEffect[i];
                if (StringUtils.isNotEmpty(coopId)) {
                    if (StringUtils.isEmpty(coopeffect)) {
                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位作用未选择");
                    }
                }
                else {
                    if (StringUtils.isNotEmpty(coopeffect)) {
                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位名称未选择");
                    }
                }
            }
        }

        if (fileAtt1 == null || fileAtt1.length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("项目可研报告未上传");
        }
        if (fileAtt2 == null || fileAtt2.length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("两评一案未上传");
        }

        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();

        /**
         * 预立项主表处理
         */
        String id = preProject.getId();
        preProject.setUptBy(vo.getId());
        preProject.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //合作单位处理
        List<PreProjectCoop> preProjectCoops = new ArrayList<PreProjectCoop>();
        if (sgCoopId != null && sgCoopId.length > 0) {
            for (int i = 0; i < sgCoopId.length; i++ ) {
                String coopId = sgCoopId[i];
                String coopeffect = coopEffect[i];
                if (StringUtils.isEmpty(coopId) && StringUtils.isEmpty(coopeffect)) {
                    continue;
                }
                String coopid = IdFactory.getUUIDUpper();//自动生成主键
                PreProjectCoop preProjectCoop = new PreProjectCoop();
                preProjectCoop.setId(coopid);
                preProjectCoop.setPreProjectId(id);
                preProjectCoop.setSgCoopId(coopId);
                preProjectCoop.setCoopEffect(coopeffect);
                preProjectCoop.setAddBy(vo.getId());
                preProjectCoop.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                preProjectCoops.add(preProjectCoop);
            }

        }

        //子项处理
        List<PreProjectSub> preProjectSubs = new ArrayList<PreProjectSub>();
        for (int i = 0; i < orderIdx.length; i++ ) {
            String orderId = orderIdx[i];
            PreProjectSub preProjectSub = new PreProjectSub();
            String subId = IdFactory.getUUIDUpper();//自动生成主键
            preProjectSub.setId(subId);
            preProjectSub.setPreProjectId(id);
            preProjectSub.setOrderIdx(Integer.parseInt(orderId));
            preProjectSub.setSubName(subName[i]);
            preProjectSub.setWorkYears(new BigDecimal(subWorkYears[i]));
            preProjectSub.setBuildYears(new BigDecimal(subBuildYears[i]));
            preProjectSub.setOmYears(new BigDecimal(subOmYears[i]));
            preProjectSub.setAddBy(vo.getId());
            preProjectSub.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            preProjectSubs.add(preProjectSub);
        }
        /**
         * 上传的文件记录加入集合
         */
        List<PreProjectAtt> fileAtts = new ArrayList<PreProjectAtt>();
        //项目可研报告
        if (fileAtt1 != null) {
            for (String file : fileAtt1) {
                PreProjectAtt preProjectAtt = createFileAtt(vo, id, file);
                fileAtts.add(preProjectAtt);
            }
        }
        //两评一案
        if (fileAtt2 != null) {
            for (String file : fileAtt2) {
                PreProjectAtt preProjectAtt = createFileAtt(vo, id, file);
                fileAtts.add(preProjectAtt);
            }
        }
        //其他资料（选填）
        if (fileAtt9 != null) {
            for (String file : fileAtt9) {
                PreProjectAtt preProjectAtt = createFileAtt(vo, id, file);
                fileAtts.add(preProjectAtt);
            }
        }
        preProjectService.editPreProject(preProject, preProjectCoops, preProjectSubs, fileAtts,submitType);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
//                "预立项 -新增预立项：项目名=" + preProject.getProName(), null);
        return RspVo.getSuccessResponse();
    }


    private PreProjectAtt createFileAtt(AuthorizationVO vo, String preProjectId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        PreProjectAtt fileAtt = new PreProjectAtt();
        if(StringUtils.isNotEmpty(fileAttStr[2])){
            fileAtt.setId(fileAttStr[2]);
        }else{
            fileAtt.setId(IdFactory.getUUIDUpper());
        }
        fileAtt.setTypes(fileAttStr[0].substring(0, 1));//资料大类：1=项目可研报告 2=两评一案 9=其他资料（选填）
        fileAtt.setPreProjectId(preProjectId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 查询所有预立项记录
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAllPreProject")
    @ResponseBody
    public Map<String, Object> getAllPreProject() {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //查询未绑定公司的项目记录
            List<PreProject> preProjects = preProjectService.selectNotBindOrg();
            map.put("preProjects", preProjects);
        }
        catch (Exception e) {
            log.error("查询所有预立项记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据id查询预立项记录
     * @return
     * @throws Exception
     */
    @RequestMapping("/getPreProjectById")
    @ResponseBody
    public Map<String, Object> getPreProjectById(String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            PreProjectVo preProjectVo = preProjectService.selectById(id);
            AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
            StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
//            preProjectVo.setStaffName(staffInfo.getStaffName());
            map.put("preProject", preProjectVo);
        }
        catch (Exception e) {
            log.error("查询预立项记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 获取名称前两字首字母
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFirstSpell")
    @ResponseBody
    public Map<String, Object> getDeptByOrgId(String name) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String firstSpell = FirstSpellUtil.two(name);
            map.put("firstSpell", firstSpell);
        }
        catch (Exception e) {
            log.error("根据类型查找公司异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 上传附件
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "preProjectAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传审预立项附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
}
